package com.huoshan.im.server.action;


import com.huoshan.im.server.ContextNaming;
import com.huoshan.im.server.action.support.StringActionSupport;
import com.huoshan.im.server.service.MessageSenderService;
import com.qy.esports.common.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import online.chazi.netkit.annotation.Inject;
import online.chazi.netkit.messaging.Message;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 火山九日
 * @version 1.0
 * @date 创建时间：2021/12/27 15:33
 * @desc 处理中转消息
 */
@Slf4j
@Inject
public class TransferMessageAction extends StringActionSupport {

    public static final String BUSINESS_ID_FIELD = "businessId";
    public static final String CONTENT_FIELD = "content";

    @Inject
    private MessageSenderService messageSenderService;

    @Override
    public void execute(String content) {

        // 过滤空消息
        if (ObjectUtils.isEmpty(content)) {
            return;
        }

        // 往repeater传递时需要带上当前用户
        Long userId = (Long) getAttribute(ContextNaming.SESSION_USER_ID);
        if (userId == null) {
            return;
        }


        // 获取需要中转的业务消息
        Map<String, Object> messageMap = JsonUtils.parse(content, Map.class);

        Map contentMap = (Map) messageMap.get(CONTENT_FIELD);
        if (ObjectUtils.isEmpty(contentMap)) {
            contentMap = new HashMap();
        }
        contentMap.put("fromUserId", userId);

        // 带上用户来源IP与PORT
        contentMap.put("ip", getAttribute(ContextNaming.SESSION_IP));
        contentMap.put("port", getAttribute(ContextNaming.SESSION_PORT));

        if (ObjectUtils.isEmpty(messageMap) || !messageMap.containsKey(BUSINESS_ID_FIELD)) {
            log.debug("chat-server中转消息失败, 未找到对应业务Id, content: {}", content);
            return;
        }

        String businessId = String.valueOf(messageMap.get(BUSINESS_ID_FIELD));
        if (!NumberUtils.isNumber(businessId)) {
            log.debug("chat-server中转消息失败, 业务Id格式错误, content: {}", content);
            return;
        }

        // 构造中转消息
        Message message = new Message(Integer.parseInt(businessId), JsonUtils.toJson(contentMap));

        // 转发消息
        messageSenderService.sendToRepeater(message);

    }
}
